package com.luzh.myspring.beans.factory.support;

import cn.hutool.core.util.StrUtil;
import com.luzh.myspring.beans.factory.DisposableBean;
import com.luzh.myspring.beans.factory.config.BeanDefinition;

import java.lang.reflect.Method;

/**
 * 销毁方法适配器
 */
public class DisposableBeanAdapter implements DisposableBean {
    private final Object bean;
    private final String beanName;
    private String destroyMethodName;

    public DisposableBeanAdapter(Object bean, String beanName, BeanDefinition beanDefinition) {
        this.bean = bean;
        this.beanName = beanName;
        this.destroyMethodName = beanDefinition.getDestroyMethodName();
    }

    @Override
    public void destroy() throws Exception {
        //DisposableBean销毁
        if (bean instanceof DisposableBean) {
            ((DisposableBean) bean).destroy();
            //执行自定义销毁
            if(StrUtil.isNotEmpty(destroyMethodName) && !"destroy".equals(this.destroyMethodName)){
                Method destroyMethod = bean.getClass().getMethod(destroyMethodName);
                destroyMethod.invoke(bean);
            }
        }else if(StrUtil.isNotEmpty(destroyMethodName)){
            Method destroyMethod = bean.getClass().getMethod(destroyMethodName);
            destroyMethod.invoke(bean);
        }
    }

}
